package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.mapper.ItemParamMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.pojo.ItemParam;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author 刘昱江
 * 时间 2021/4/7
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private ItemParamMapper itemParamMapper;

    @Override
    public PageResult selectItemList(PageResult pageResult) {
        //实现分页查询数据
        Page page = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        //如果商品标题不为null则进行模糊查询
        queryWrapper.like(StringUtils.hasLength(pageResult.getQuery()), "title", pageResult.getQuery());
        page = itemMapper.selectPage(page,queryWrapper);
        //获取分页之后的数据
        pageResult.setTotal(page.getTotal())
                  .setRows(page.getRecords());
        return pageResult;
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {

        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {

        //关联删除数据
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
        itemParamMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        //1.实现商品入库操作
        Item item = itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);

        //2.实现商品详情入库
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);

        //3.实现商品参数入库
        ItemParam itemParam = itemVO.getItemParam();
        //将数据转化为JSON
        String dynamicArgs = ObjectMapperUtil.toJSON(itemParam.getDynamicArray());
        String staticArgs  = ObjectMapperUtil.toJSON(itemParam.getStaticArray());
        itemParam.setDynamicArgs(dynamicArgs);
        itemParam.setStaticArgs(staticArgs);
        itemParam.setId(item.getId());
        itemParamMapper.insert(itemParam);
    }
}
